package io.boot.modules.msg.service.impl;

import io.boot.common.utils.SpringContextUtils;
import io.boot.modules.msg.service.MessageService;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author kyson
 * @date 2020/04/26 09:18
 */
@ServerEndpoint("/ws/msg/{uid}")
@Component
public class WebSocketMsgServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketMsgServer> webSocketSet = new CopyOnWriteArraySet<>();
    /**
     * 以用户的id为key，WebSocket为对象保存起来
     */
    private static Map<String, WebSocketMsgServer> clients = new ConcurrentHashMap<String, WebSocketMsgServer>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    /**
     * 接收sid
     */
    private String uid="";




    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("uid") String uid) throws InterruptedException {
        this.session = session;
        this.uid=uid;
        clients.put(uid,this);
//        boolean flag=true;
//        for (WebSocketMsgServer item : webSocketSet) {
//            if(item.uid.equals(uid)){
//                flag=false;
//                break;
//            }
//        }
//        if(flag){
//            webSocketSet.add(this);
//        }
        Thread.currentThread().sleep(5000);
        MessageService messageService= (MessageService) SpringContextUtils.getBean("messageService");
        messageService.sendMsg(Long.valueOf(uid));
//        addOnlineCount(); //在线数加1
//        System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
//        sendMessage("有新连接加入！当前在线人数为" + getOnlineCount());
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        clients.remove(this.uid);
//        webSocketSet.remove(this); //从set中删除
        subOnlineCount(); //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }



    /**
     * 异常推送
     * @param session session
     * @param error 异常
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 发送信息
     * @param message 信息
     * @throws IOException IO异常
     */
    private void sendMessage(String message)  {
//            this.session.getBasicRemote().sendText(message);
        try {
            this.session.getAsyncRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //this.session.getAsyncRemote().sendText(message);
    }

    /**
     * 群发自定义消息(uid ==0 就是群发)
     * */
    public static Boolean sendInfo(String message,@PathParam("uid") String uid){
//        boolean flag=false;
//        for (WebSocketMsgServer item : webSocketSet) {
//            try {
//                if(uid.equals("0")) {
//                    item.sendMessage(message);
//                }else if(item.uid.equals(uid)){
//                    item.sendMessage(message);
//                    flag=true;
//                }
//            } catch (Exception e) {
//                continue;
//            }
//        }
//        return flag;
        try {
            clients.get(uid).sendMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketMsgServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketMsgServer.onlineCount--;
    }
}
